package com.education.welco.controller;

import com.education.common.pojo.AjaxResult;
import com.education.common.utils.StringUtils;
import com.education.utils.FileUtils;
import com.education.welco.enums.FileTypeEnum;
import com.education.welco.pojo.PlatResourceShare;
import com.education.welco.pojo.PlatformResources;
import com.education.welco.pojo.vo.PlatResourceShareVo;
import com.education.welco.pojo.vo.ShareSchoolVo;
import com.education.welco.service.IPlatResourceShareService;
import com.education.welco.service.IPlatformResourcesService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

import static com.education.welco.pojo.consts.FileConst.*;

/**
 * 平台资源共享 controller业务
 *
 * @Author: liftsail
 * @Date: 2022-09-28
 * @Description: 不积跬步无以至千里
 */
@RestController
@RequestMapping("/platResourceShare")
public class PlatResourceShareController {

    @Autowired
    private IPlatResourceShareService platResourceShareService;

    @Autowired
    private IPlatformResourcesService platformResourcesService;

    //查询学校   /api/wisdom/jrSchool/selectAll
    //select id, school_phone, school_name, create_time, introduction, logo, type from jr_school

    //学校下拉列表
    //TODO 分享学校回调
    @GetMapping("/shareSchoolList")
    public AjaxResult shareSchoolList() {
        List<ShareSchoolVo> shareSchoolVoList = platResourceShareService.selectShareSchoolList();
        return AjaxResult.success(shareSchoolVoList);
    }


    /**
     * 列表查询平台资源共享
     * 平台资源左侧共享文件列表查询
     * 显示资源分享到哪些学校
     * sql嵌套sql
     * sharerId
     */
    @GetMapping("/list")
    public AjaxResult list(@RequestParam("sharerId") Integer sharerId,
                           @RequestParam(value = "fileName", required = false) String fileName,
                           @RequestParam(value = "fileType", required = false) FileTypeEnum fileType,
                           @RequestParam(value = "pageNum", required = false) Integer pageNum,
                           @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        if (fileType != null && StringUtils.isNotEmpty(fileName)) {
            //后缀和名字
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = platResourceShareService.selectShareSchoolResListBySharerId(sharerId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(sharerId, ridCollect, fileName, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        }
        //根据fileName是否存在进入不同的业务逻辑
        else if (fileType != null) {
            //后缀查询
            if (fileType == FileTypeEnum.ALL) {
                //没条件
                List<PlatformResources> platResourceShareList = platResourceShareService.selectShareSchoolResListBySharerId(sharerId, pageNum, pageSize);
                PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
                return AjaxResult.success("查询成功！", platformResourcesPageInfo);
            }
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = platResourceShareService.selectShareSchoolResListBySharerId(sharerId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(sharerId, ridCollect, null, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else if (StringUtils.isNotEmpty(fileName)) {
            //模糊查
            List<PlatformResources> platformResourcesList = platResourceShareService.selectShareSchoolResListBySharerId(sharerId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(sharerId, ridCollect, fileName, null, null, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else {
            //没条件
            List<PlatformResources> platResourceShareList = platResourceShareService.selectShareSchoolResListBySharerId(sharerId, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        }
    }


    /**
     * 新增保存平台资源共享
     *
     * @Param sharerId 平台管理员id(分享者)
     * @Param resId 资源id(平台资源id) *
     * @Param receiverId 学校id(接收者) *
     */
    @PostMapping("/addShare")
    public AjaxResult addSave(@RequestBody PlatResourceShareVo platResourceShareVo) {
        //检查用户是否之前存在
        PlatResourceShare platResourceShare = platResourceShareService.selectPlatResourceShareByShareIdAndResIdAndReceiveId(platResourceShareVo.getSharerId(), platResourceShareVo.getResId(), platResourceShareVo.getReceiverId());
        //存在走修改状态业务
        if (Objects.nonNull(platResourceShare)) {
            PlatResourceShare platResourceSharecp = new PlatResourceShare();
            platResourceSharecp.setSharerId(platResourceShare.getSharerId());
            platResourceSharecp.setResId(platResourceShare.getResId());
            platResourceSharecp.setReceiverId(platResourceShare.getReceiverId());
            platResourceSharecp.setIsDelete(false);
            platResourceShareService.updatePlatResourceShareByShareIdAndResIdAndReceiveId(platResourceSharecp);
            //方法调用
            updatePlatResSharedState(new ArrayList<String>() {
                {
                    add(platResourceShare.getResId());
                }
            });
            //状态判定
            if (platResourceShare.getIsDelete()) {
                return AjaxResult.success("资源共享成功！");
            }
            return AjaxResult.success("资源取消共享成功！");
        }
        //不存在走新增业务
        platResourceShareService.insertPlatResourceShare(platResourceShareVo);
        //直接修改为共享状态
        platformResourcesService.updatePlatformResourcesByIdListForShareState(new ArrayList<String>() {
            {
                add(platResourceShareVo.getResId());
            }
        }, true);
        return AjaxResult.success("资源共享成功！");
    }


    /**
     * 批量新增保存资源用户星标（收藏关联）
     *
     * @Param sharerId 平台管理员id(分享者)
     * @Param resIdList 资源id集合(平台资源id) *
     * @Param receiverId 学校id(接收者) *
     */
    @PostMapping("/batch/addShare")
    public AjaxResult batchAddSave(@RequestBody PlatResourceShareVo platResourceShareVo) {
        //检查用户之前已经星标资源列表
        List<PlatResourceShare> platResourceShareListBefore = platResourceShareService.selectPlatResourceShareByShareIdAndResIdListAndReceiveId(platResourceShareVo.getSharerId(), platResourceShareVo.getResIdList(), platResourceShareVo.getReceiverId());
        List<String> resIdListBefore = platResourceShareListBefore.parallelStream().map(platResourceShare -> platResourceShare.getResId()).collect(Collectors.toList());
        //现在需要星标的资源id
        List<String> resIdListUserNow = platResourceShareVo.getResIdList();
        //从现在列表中移除数据库中存在的
        resIdListUserNow.removeIf(resId -> resIdListBefore.contains(resId));

        //1.批量更改状态-resIdListBefore
        int i = platResourceShareService.batchUpdatePlatResourceShareByShareIdAndResIdListAndReceiveId(platResourceShareVo.getSharerId(), resIdListBefore, platResourceShareVo.getReceiverId(), false);
        //方法调用
        if (resIdListBefore != null && resIdListBefore.size() > 0) {
            updatePlatResSharedState(new ArrayList<>(resIdListBefore));
        }
        //2.批量插入数据-resIdListUserNow
        if (resIdListUserNow != null && resIdListUserNow.size() > 0) {
            int j = platResourceShareService.batchInsertPlatResourceShareByShareIdAndResIdListAndReceiveId(platResourceShareVo.getSharerId(), resIdListUserNow, platResourceShareVo.getReceiverId(), false);
            platformResourcesService.updatePlatformResourcesByIdListForShareState(new ArrayList<>(resIdListUserNow), true);
        }
        return AjaxResult.success("批量共享成功！");
    }


    /**
     * 修改平台资源表的资源共享状态
     * 查找共享表的共享个数
     */
    public void updatePlatResSharedState(List<String> resIdList) {
        //查找有效的分享次数-返回都是被分享的
        List<PlatResourceShare> platResourceShareList = platResourceShareService.selectPlatResourceShareByResIdAndisDelete(resIdList, false);
        List<String> sharedResId = platResourceShareList.parallelStream().map(platResourceShare -> platResourceShare.getResId()).collect(Collectors.toList());
        //更新两次
        //1.被共享
        if (sharedResId.size() > 0) {
            int i = platformResourcesService.updatePlatformResourcesByIdListForShareState(sharedResId, true);
        }
        //2.未共享
        resIdList.removeIf(resId -> sharedResId.contains(resId));
        if (resIdList.size() > 0) {
            int j = platformResourcesService.updatePlatformResourcesByIdListForShareState(resIdList, false);
        }
    }


    /**
     * 主键详情平台资源共享
     */
    @GetMapping("/selectOne")
    public AjaxResult selectOne(Integer id) {
        PlatResourceShare result = platResourceShareService.selectPlatResourceShareById(id);
        return AjaxResult.success("查询成功！", result);
    }

    /**
     * 修改保存平台资源共享
     */
    @PostMapping("/update")
    public AjaxResult editSave(@RequestBody PlatResourceShare platResourceShare) {
        platResourceShareService.updatePlatResourceShare(platResourceShare);
        return AjaxResult.success("修改成功！");
    }

    /**
     * 删除平台资源共享
     */
    @PostMapping("/del")
    public AjaxResult remove(String ids) {
        platResourceShareService.deletePlatResourceShareByIds(ids);
        return AjaxResult.success("删除成功！");
    }


    /**
     * 老师端查找学校资源-我的资源
     * 共享到学校的资源查询 老师id-学校id-资源id-资源表
     * schoolId-学校idInteger pageNum, Integer pageSize
     */
    @GetMapping("/shareSchResList")
    public AjaxResult shareSchResList(@RequestParam("schoolId") Integer schoolId,
                                      @RequestParam("teaId") Integer teaId,
                                      @RequestParam(value = "fileName", required = false) String fileName,
                                      @RequestParam(value = "fileType", required = false) FileTypeEnum fileType,
                                      @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                      @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        if (fileType != null && StringUtils.isNotEmpty(fileName)) {
            //名字和后缀
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = platResourceShareService.selectShareSchoolResListBySchoolId(schoolId, teaId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(teaId, ridCollect, fileName, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        }
        //根据fileName是否存在进入不同的业务逻辑
        else if (fileType != null) {
            //后缀查询
            if (fileType == FileTypeEnum.ALL) {
                //没条件
                List<PlatformResources> platResourceShareList = platResourceShareService.selectShareSchoolResListBySchoolId(schoolId, teaId, pageNum, pageSize);
                PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
                return AjaxResult.success("查询成功！", platformResourcesPageInfo);
            }
            Set<String> extensionSet = FileUtils.getFileExtensionsByType(fileType);
            List<PlatformResources> platformResourcesList = platResourceShareService.selectShareSchoolResListBySchoolId(schoolId, teaId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            //文件类型关于in|not in的判断
            Boolean inOrNot = true;
            if (fileType == FileTypeEnum.OTHER) {
                inOrNot = false;
            }
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(teaId, ridCollect, null, extensionSet, inOrNot, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else if (StringUtils.isNotEmpty(fileName)) {
            //模糊查
            List<PlatformResources> platformResourcesList = platResourceShareService.selectShareSchoolResListBySchoolId(schoolId, teaId, null, null);
            List<String> ridCollect = platformResourcesList.stream().map(platformResources -> platformResources.getId()).collect(Collectors.toList());
            List<PlatformResources> platResourceShareList = platformResourcesService.selectShareSchoolResListBySchoolIdAndFileName(teaId, ridCollect, fileName, null, null, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        } else {
            //没条件
            List<PlatformResources> platResourceShareList = platResourceShareService.selectShareSchoolResListBySchoolId(schoolId, teaId, pageNum, pageSize);
            PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
            return AjaxResult.success("查询成功！", platformResourcesPageInfo);
        }
    }


    /**
     * 保留文件层级关系同时要筛选文件类型
     * 老师端查找学校资源-我的资源
     * 共享到学校的资源查询 老师id-学校id-资源id-资源表
     * schoolId-学校idInteger pageNum, Integer pageSize
     */
    @GetMapping("/shareSchResListForNet2Filter")
    public AjaxResult shareSchResListForNet2Filter(@RequestParam("schoolId") Integer schoolId,
                                                   @RequestParam("teaId") Integer teaId,
                                                   @RequestParam(value = "fileName", required = false) String fileName,
                                                   @RequestParam(value = "fileType", required = false) FileTypeEnum fileType,
                                                   @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                                   @RequestParam(value = "pageSize", required = false) Integer pageSize) {
        List<PlatformResources> platResourceShareList = platResourceShareService.selectShareSchoolResListBySchoolId(schoolId, teaId, pageNum, pageSize);
        PageInfo<PlatformResources> platformResourcesPageInfoOld = new PageInfo<>(platResourceShareList);
        //过滤不满足文件后缀的文件   IMG_FILE   VIDEO_FILE   DOC_FILE
        Set<String> suffixSet = new HashSet<>(2);
        if (fileType == FileTypeEnum.IMAGE) {
            suffixSet.addAll(IMG_FILE);
        } else if (fileType == FileTypeEnum.VIDEO) {
            suffixSet.addAll(VIDEO_FILE);
        } else if (fileType == FileTypeEnum.DOC) {
            suffixSet.addAll(DOC_FILE);
        }
        platResourceShareList = platResourceShareList.parallelStream().filter(platformResources -> platformResources.getIsDir() || suffixSet.contains(platformResources.getExtension())).collect(Collectors.toList());
        PageInfo<PlatformResources> platformResourcesPageInfo = new PageInfo<PlatformResources>(platResourceShareList);
        platformResourcesPageInfo.setTotal(platformResourcesPageInfoOld.getTotal());
        return AjaxResult.success("查询成功！", platformResourcesPageInfo);
    }
}